package com.magic.zhixin.service;

import com.magic.zhixin.entity.Result;
import com.magic.zhixin.entity.UserInfo;
import com.magic.zhixin.entity.UserTopic;
import com.magic.zhixin.entity.UserTopicDetail;
import com.magic.zhixin.repository.UserTopicDetailRepository;
import com.magic.zhixin.repository.UserTopicRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ZhiXinLiuYanService {
    @Autowired
    private UserTopicRepository userTopicRepository;
    @Autowired
    private UserTopicDetailRepository userTopicDetailRepository;

    @Transactional
    public Result<UserTopic> addUserTopic(String title, UserInfo userInfo) {
        UserTopic userTopic = new UserTopic();
        userTopic.setTitle(title);
        userTopic.setUserId(userInfo.getId());
        userTopic.setIsHot(false);
        userTopic.setAvatar(userInfo.getAvatar());
        userTopic.setNickName(userInfo.getNickname());
        userTopicRepository.save(userTopic);
        return Result.OkResult(userTopic);
    }

    public Result<UserTopic> getUserTopic(UserInfo userInfo) {
        return Result.OkResult(userTopicRepository.findByUserId(userInfo.getId()));
    }

    @Transactional
    public Result<UserTopicDetail> addComment(String content, UserInfo userInfo,Long userTopicId) {
        UserTopicDetail userTopicDetail = new UserTopicDetail();
        userTopicDetail.setUserTopicId(userTopicId);
        userTopicDetail.setCommenterAvatar(userInfo.getAvatar());
        userTopicDetail.setCommenterName(userInfo.getNickname());
        userTopicDetail.setContent(content);
        userTopicDetailRepository.save(userTopicDetail);
        return Result.OkResult(userTopicDetail);
    }

    public Result<UserTopicDetail> getAllUserTopicDetail(Long userTopicId) {
        List<UserTopicDetail> userTopicDetails = userTopicDetailRepository.findByUserTopicId(userTopicId);
        return Result.OkResult(userTopicDetails);
    }

    public Result<UserTopic> getHotUserTopic() {
        return Result.OkResult(userTopicRepository.findByIsHot(Boolean.TRUE));
    }
}
